﻿using AuthCenter.Api.Read.Application.Command.Role;
using AuthCenter.Api.Read.Application.Output;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;

namespace AuthCenter.Api.Read.Application.Hander.Role
{
    public class GetUserIdsByRoleIdHander : IRequestHandler<GetUserIdsByRoleIdCommand, ApiResult<List<UserRoleOutput>>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepository;
        private readonly IBaseRepository<UserRoleModel> _userRoleRepository;
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        public GetUserIdsByRoleIdHander(IBaseRepository<RoleModel> roleRepository, IMapper mapper, IBaseRepository<UserRoleModel> userRoleRepository, IBaseRepository<UserModel> userRepository)
        {
            _roleRepository = roleRepository;
            _mapper = mapper;
            _userRoleRepository = userRoleRepository;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 获取用户角色
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public Task<ApiResult<List<UserRoleOutput>>> Handle(GetUserIdsByRoleIdCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<UserRoleOutput>> res = new ApiResult<List<UserRoleOutput>>();
            var userIds = _userRoleRepository.GetAll()
                .Where(x => x.RoleId ==request. roleId && !x.IsDeleted);
            var model = _mapper.Map<List<UserRoleOutput>>(userIds);
            foreach (var item in model)
            {
                item.UserId = _userRepository.GetAll().Where(x => x.Id == item.UserId).Select(x => x.Id).FirstOrDefault();
                item.UserName = _userRepository.GetAll().Where(x => x.Id == item.UserId).Select(x => x.UserName).FirstOrDefault();
                item.DepartmentId = _userRepository.GetAll().Where(x => x.Id == item.UserId).Select(x => x.DepartmentId).FirstOrDefault();
            }
            res.Message = "根据角色id获取用户id";
            res.Code = ApiEnums.OK;
            res.Data = model;
            return Task.FromResult(res);
        }
    }
}
